import Vue from "vue";
import VueRouter from "vue-router";
import { getToken } from "../utils/cookies";
Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      name: "Layout",
      component: () => import("../layout/Layout.vue"),
      redirect: "/home",
      children: [
        {
          path: "home",
          name: "Home",
          component: () => import("../views/home/Home.vue"),
        },
        {
          path: "student",
          name: "Student",
          component: () => import("../views/student/Student.vue"),
        },
        {
          path: "teacher",
          name: "Teacher",
          component: () => import("../views/teacher/Teacher.vue"),
        },
        {
          path: "course",
          name: "Course",
          component: () => import("../views/course/Course.vue"),
        },
        {
          path: "order",
          name: "Order",
          component: () => import("../views/order/Order.vue"),
        },
        {
          path: "finance",
          name: "Finance",
          component: () => import("../views/finance/Finance.vue"),
        },
        {
          path: "setting",
          name: "Setting",
          component: () => import("../views/setting/Setting.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "Login",
      component: () => import("../views/login/Login.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () => import("../views/login/register.vue"),
    },
  ],
});

// 设置白名单  未登录 可跳转的页面
let whileArr = ["/login", "/register"];
// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  // 设置当前你所在的页面 路由mypath
  let mypath = to.path;
  // 使用cookie 获取输入的token
  let token = getToken("token");
  if (token) {
    next();
  } else {
    //     //没登录
    if (whileArr.includes(mypath)) {
      next();
    } else {
      next("/login");
    }
    //     // 向后端发送一个token
  }
});
export default router;
